package com.example.backblog.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Map;

/**
 * @description: 体系管理的repository配置
 * @Date: 2020/11/11 14:25
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryMain",
        transactionManagerRef="transactionManagerMain",
        basePackages = { "com.example.backblog.repository"})
public class MainRepositoryConfig {

    @Autowired
    @Qualifier("mainDataSource")
    private DataSource systemDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;

    /**
     * 使用@Primary标记主数据源
     * @bean中name与顶部配置需要一致
     * @param builder
     * @return
     */
    @Primary
    @Bean(name = "entityManagerFactoryMain")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySystem(
            EntityManagerFactoryBuilder builder) {
        //网上文章大多数都是jpaProperties.getHibernateProperties(dataSource);就直接得到了hibernate的配置map，
        //但这个方法在springboot2.0+好像就舍弃了，所以这里改成这样。
        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
        return builder.dataSource(systemDataSource).properties(properties)
                //实体包路径
                .packages("com.example.backblog.entity").build();
    }

    @Primary
    @Bean(name = "transactionManagerMain")
    public PlatformTransactionManager transactionManagerSystem(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorySystem(builder).getObject());
    }
}
